package com.example.mobilesafe;

import android.app.Application;
import android.os.Environment;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        // 1.捕获全局（应用任意模块）异常
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
                // 获取到了未捕获的异常，处理方法
                e.printStackTrace();
                // 将捕获的异常存储到sd卡中
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "error.log";
                File file = new File(path);
                try {
                    PrintWriter printWriter = new PrintWriter(file);
                    e.printStackTrace(printWriter);
                    printWriter.close();
                } catch (FileNotFoundException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
